package qe.spider.grab;

import cn.hutool.core.text.UnicodeUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


//查股网-添加自选股
@Slf4j
public class GrabGubit_AddZiXuan {


    private FormBody formBody(List<String> stockCodes) {
        FormBody formBody = new FormBody.Builder()
                .add("t", "1")
                .add("code", stockCodes.stream().collect(Collectors.joining(",")))
                .build();
        return formBody;
    }

    public void grab(List<String> stockCodes) throws IOException {
        String cookie = "gpai_auth=" + GrabGubit.cookies.get("gpai_auth") +
                "; PHPSESSID=" + GrabGubit.cookies.get("PHPSESSID") +
                "; user=" + GrabGubit.cookies.get("user") +
                "; zhuser=" + GrabGubit.cookies.get("zhuser");

        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://ddx.gubit.cn/import.php")
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Cookie", cookie)
                .header("Host", "ddx.gubit.cn")
                .header("Origin", "http://ddx.gubit.cn")
                .header("Pragma", "no-cache")
                .header("Referer", "http://ddx.gubit.cn/zixuan.php")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.140")
                .post(formBody(stockCodes))
                .build();
        Gson gson = new Gson();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);


            String result = UnicodeUtil.toString(response.body().string());
            log.info("添加自选返回：{}", result);
            JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
            String status = jsonObject.getAsJsonPrimitive("status").getAsString();
            if (!"1".equals(status)) throw new IOException("查股网返回状态错误：" + result);
        }

    }
}
